import md5 from 'js-md5'
import { getLang } from './lang';

export function generateMd5(str: string) {
  return md5(str)
}

/**
 * 获取本地图
 * @param name // 文件名 如 doc.png
 * @returns {*|string}
 */
export function getAssetsImages(name: string) {
  return new URL(`/src/assets/images/${name}`, import.meta.url).href;
}

export function getTimeRange() {
  // 获取当前时间
  const now = new Date();
  // 获取当前小时数
  const hour = now.getHours();
  // 判断是早上、中午还是晚上
  let period;
  if (hour >= 6 && hour < 12) {
    period = '早上';
  } else if (hour >= 12 && hour < 18) {
    period = '中午';
  } else {
    period = '晚上';
  }
  return period;
}

export function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

/**
 * 美国和加拿大：+1
中国：+86
中国香港：+852
日本：+81
印度：+91
巴西：+55
英国：+44
德国：+49
法国：+33
澳大利亚：+61
南非：+27
 */
export const countryCodes = ["+86", "+852", "+1", "+44", "+81", "+91", "+55", "+44", "+49", "+33", "+61", "+27"];

export function getMobilePhoneInfo(phoneNumber: string) {
  // const phoneNumber = "+8613911111111";
  countryCodes.sort((a, b) => b.length - a.length);  // 按照长度从长到短排序

  let areaCode = "";
  let newPhoneNumber = "";
  for (let code of countryCodes) {
    if (phoneNumber.startsWith(code)) {
      areaCode = code;
      newPhoneNumber = phoneNumber.split(code)[1];
      break;
    }
  }
  return {
    areaCode,
    phoneNumber: newPhoneNumber
  }
}

export function maskBankCard(cardNumber: string) {
  let length = cardNumber.length;
  let lastFour = cardNumber.substring(length - 4, length);
  let masked = "";
  for (let i = 0; i < length - 4; i++) {
      masked += "*";
  }
  masked += lastFour;
  return masked;
}

export function formatCurrency(num: any) {
  num = num.toString().replace(/\$|\,/g,'');
  if (isNaN(num)) num = "0";
  num = parseFloat(num).toFixed(2);
  var sign = (num == (num = Math.abs(num)));
  num = Math.floor(num * 100 + 0.50000000001);
  var cents: string | number = num % 100;
  num = Math.floor(num / 100).toString();
  if (cents < 10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
      num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
  }
  return (((sign) ? '' : '-') + num + '.' + cents);
}

export function formatDateUTCISO8601(date: string) {
  let specificDate = new Date(date);

  // 使用 setHours 方法将时间设置为 "00:00:00"。
  specificDate.setHours(0, 0, 0, 0);

  // 获得时区差值（分钟）
  let timezoneOffsetMinutes = specificDate.getTimezoneOffset();

  // 根据时区差值调整日期
  specificDate.setMinutes(specificDate.getMinutes() - timezoneOffsetMinutes);

  // 再次将时间设置为 "00:00:00"，以避免时区差值的影响
  specificDate.setHours(0, 0, 0, 0);

  // 将日期时间转换为 RFC 3339 格式
  let rfc3339 = specificDate.toISOString();
  return rfc3339;
}

function getLanguageFromUrl() {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get('lang');
}

function getLanguageFromCookie() {
  return getLang();
}

function getLanguageFromBrowser() {
  return navigator.language;
}

// zh_CN zh_HK,en,my
export function getLanguage() {
  let language = getLanguageFromUrl();
  if (!language) {
      language = getLanguageFromCookie();
      if (!language) {
          language = getLanguageFromBrowser();
      }
  }
  return language || 'zh_CN';
}


export function objectToQueryString(obj: any) {
  return Object.entries(obj)
    .map(([key, value]: any[]) => [encodeURIComponent(key), encodeURIComponent(value)].join('=') )
    .join('&');
}


export async function copyTextToClipboard(text: string) {
  let isSuccessful = false;

  // 检查 navigator.clipboard 是否可用
  if (navigator.clipboard) {
    // 使用现代 Clipboard API
    try {
      await navigator.clipboard.writeText(text);
      console.log('Text successfully copied');
      isSuccessful = true;
    } catch (err) {
      console.error('Oops, unable to copy', err);
      isSuccessful = false;
    }
  } else {
    // 回退使用 document.execCommand
    const textArea = document.createElement("textarea");

    // 隐藏 textarea 元素
    textArea.style.position = 'fixed';
    textArea.style.left = '0';
    textArea.style.top = '0';
    textArea.style.opacity = '0';

    textArea.value = text;

    document.body.appendChild(textArea);

    textArea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        console.log('Text successfully copied');
        isSuccessful = true;
      } else {
        console.log('Unable to copy text');
        isSuccessful = false;
      }
    } catch (err) {
      console.error('Oops, unable to copy', err);
      isSuccessful = false;
    }

    document.body.removeChild(textArea);
  }

  return isSuccessful;
}
